<?php
namespace App\Controller\App;

use App\Query\MallGoodsQuery;
use App\Query\MallShopQuery;
use App\Query\MallOrderQuery;
use App\Repository\MallShopRepository;
use App\Repository\MallOrderRepository;
use App\Repository\MallGoodsRepository;
use App\Request\MallShopRequest;
use App\Request\MallGoodsRequest;

class MallShopController extends Controller
{
    // 我的店铺
    public function index()
    {
        return $this->user()->model();
    }
    
    // 我的店铺
    public function user()
    {
        if(!$shop = MallShopQuery::user($this->auth())->first())
        {
            $this->error('shop');
        }
        
        $shop = MallShopRepository::make($shop);
        
        // 判断状态
        if(!$shop->statusOk())
        {
            $this->error('shop_status'); 
        }
        
        return $shop;
    }
    
    // 申请店铺
    public function create(MallShopRequest $request)
    {
        // 判断是否有店铺
        if($shop = MallShopQuery::user($this->auth())->first())
        {
            $this->error('shop_create');
        }
        
        if(MallShopRepository::make()->create($this->auth(), $request->validated()))
        {
            $this->message('ok');
        }
        
        $this->error('error');
    }
    
    // 我的商品
    public function goods()
    {
        return MallGoodsQuery::shop($this->user())->paginate(10)->toArray();
    }
    
    // 创建商品
    public function goodsCreate(MallGoodsRequest $request)
    {
        if(MallGoodsRepository::make()->create($request->validated(), $this->user()))
        {
            $this->message('create');
        }
        
        $this->error('create');
    }
    
    // 商品删除
    public function goodsDelete($id)
    {
        if($goods = MallGoodsQuery::shop($this->user())->find($id))
        {
            MallGoodsRepository::make($goods)->delete();
            
            $this->message('delete');
        }
        
        $this->error('delete');
    }
    
    // 商品库存
    public function goodsCount($id)
    {
        if($goods = MallGoodsQuery::shop($this->user())->find($id))
        {
            MallGoodsRepository::make($goods)->addCount((int) $this->input('count'));
            
            $this->message('ok');
        }
        
        $this->error('error');
    }
    
    // 我的订单
    public function order()
    {
        return MallOrderQuery::query(
            MallOrderQuery::shop($this->user()),
            $this->inputs('status')
        )->paginate(10)->toArray();
    }
    
    // 发货
    public function orderExpress($id)
    {
        if($model = MallOrderQuery::shop($this->user())->find($id))
        {
            if(MallOrderRepository::make($model)->setExpress($this->input('name'), $this->input('code')))
            {
                $this->message('ok');
            }
        }
        
        $this->error('error');
    }
}
